package com.treeroot.treenet.common.utils;

import cn.hutool.json.JSONUtil;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Create By TreeRoot
 * Create Time: 2023/12/18 03:37
 * Class Name: WebUtils
 * Description:
 * Web工具
 * @author TreeRoot
 */
public class WebUtils implements HttpHandler {
    private static final Logger log = LoggerFactory.getLogger(WebUtils.class);

    /**
     * 将字符串渲染到客户端
     *
     * @param response 渲染对象
     * @param string   待渲染的字符串
     * @return null
     */
    public static String renderString(HttpServletResponse response, String string) {
        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        } catch (IOException e) {
            log.error("ERRORMESSAGE===>{}", JSONUtil.toJsonStr(e));
        }
        return null;
    }

    /**
     * 处理进来的请求
     *
     * @param exchange the exchange containing the request from the
     *                 client and used to send the response
     */
    @Override
    public void handle(HttpExchange exchange) throws IOException {
        log.info("开始处理HandleHttpRequest.handleRequest");
        String requestBody = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
        log.info("请求正文内容：" + requestBody);
        log.info("请求头信息：" +JSONUtil.toJsonStr(exchange.getRequestHeaders()));
        log.info("请求协议：" + exchange.getProtocol());
        log.info("请求地址"+ exchange.getRequestHeaders().get("Host"));
        log.info("请求头携带的token"+ exchange.getRequestHeaders().get("token"));
        log.info("请求URI：" + exchange.getRequestURI().toString());
        log.info("远程地址：" + exchange.getRemoteAddress());
        log.info("请求方法：" + exchange.getRequestMethod());
        String response = "Hello World!";
        exchange.sendResponseHeaders(200, response.getBytes().length);
        exchange.getResponseBody().write(response.getBytes());
        exchange.close();
    }
}
